<script setup>
import { onMounted, ref, onUnmounted, onBeforeUnmount } from "vue";
import "cesium/Build/Cesium/Widgets/widgets.css";
import * as Cesium from "cesium";
import { ElMessage, ElNotification } from "element-plus";
import CircleDiffusion from "@/utils/cesiumCtrl/diffuse.js";

let viewer = null;
let tileset = null;

onMounted(() => {
  initCesium();
});

const initCesium = async () => {
  Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2MzU4NzcwYS0yYjhjLTQ3ZTYtOGM4OC0yMjViMzg5YWNiM2MiLCJpZCI6MTgxMzU5LCJpYXQiOjE3MDE3MDIxNTd9.nMroTGyHYS7g3jjRX2HMLkAA1bbHMfEuTBLH2BCYAuM";

  viewer = new Cesium.Viewer("scene");
  tileset = await Cesium.Cesium3DTileset.fromUrl("/data/tileset.json", {
    skipLevelOfDetail: true,
    baseScreenSpaceError: 1024,
    skipScreenSpaceErrorFactor: 16,
    skipLevels: 1,
    immediatelyLoadDesiredLevelOfDetail: false,
    loadSiblings: false,
    cullWithChildrenBounds: true,
  });

  // 添加
  viewer.scene.primitives.add(tileset);
  viewer.zoomTo(tileset);
  // const boundingSphere = tileset.boundingSphere;
  // 定位
  // viewer.camera.flyToBoundingSphere(
  //   boundingSphere,
  //   new Cesium.HeadingPitchRange(0.0, -0.5, boundingSphere.radius)
  // );
  tileset.allTilesLoaded.addEventListener(function () {
    ElMessage({
      message: "加载成功",
      type: "success",
    });
  });

  const circleDiffusion = new CircleDiffusion(viewer, "circle");
  circleDiffusion.add(
    [113.06270169625013, 22.646124636731052, 0],
    "#F7EB08",
    100,
    5000
  );
  // Shade selected model with highlight.
  const fragmentShaderSource = `
  uniform sampler2D colorTexture;
  in vec2 v_textureCoordinates;
  uniform vec4 highlight;
  void main() {
      vec4 color = texture(colorTexture, v_textureCoordinates);
      if (czm_selected()) {
          vec3 highlighted = highlight.a * highlight.rgb + (1.0 - highlight.a) * color.rgb;
          out_FragColor = vec4(highlighted, 1.0);
      } else { 
          out_FragColor = color;
      }
  }
  `;

  const stage = viewer.scene.postProcessStages.add(
    new Cesium.PostProcessStage({
      fragmentShader: fragmentShaderSource,
      uniforms: {
        highlight: function () {
          return new Cesium.Color(1.0, 0.0, 0.0, 0.5);
        },
      },
    })
  );
  stage.selected = [];
  // 开启深度检测

  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler.setInputAction(function (event) {
    const feature = viewer.scene.pick(event.position);

    dilog(feature, event);
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  const dilog = (feature, position) => {
    if (Cesium.defined(feature)) {
      // stage.selected = [feature.primitive];
      /*  let cartesian = viewer.scene.pickPosition(position.position);

      let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        // 弧度转为角度（经纬度）
        let lon = Cesium.Math.toDegrees(cartographic.longitude);
        let lat = Cesium.Math.toDegrees(cartographic.latitude);
        //模型高度
        let height = cartographic.height;  
        console.log('模型表面的经纬度高程是：', { x: lon, y: lat, height: height }) */

      const { x, y } = position.position;
      ElNotification({
        title: "选择了倾斜摄影tileset",
        message: `位置在${x},${y}`,
        type: "info",
      });
    } else {
      stage.selected = [];
    }
  };
};

onBeforeUnmount(() => {
  tileset && tileset.destroy();
});
</script>

<template>
  <div id="scene" style="height: 100vh; width: 100vw"></div>
</template>

<style scoped lang="scss">
.read-the-docs {
  color: #888;
}
</style>
